package quan.dong.handle;

import android.os.Handler;
import android.os.Message;
import quan.dong.common.Common;
import quan.dong.common.CommonEnums;
import quan.dong.common.Constant;
import quan.dong.common.TCPSocket;

public class Login implements Runnable {
	String imeiNumber;
	String phoneNumber;
	Thread runner;
	TCPSocket socket;
	Handler handler;

	public Login(String imeiNumber, String phoneNumber, Handler handler,
			String threadName) {
		super();
		this.phoneNumber = phoneNumber;
		this.handler = handler;
		this.imeiNumber = imeiNumber;
		runner = new Thread(this, threadName);
		System.out.println(runner.getName());
		runner.start();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

		try {
			TCPSocket socket = new TCPSocket();
			boolean isConnected = socket.Create(Constant.SERVER_IP_ADDRESS,
					Constant.PORT);
			if (isConnected) {
				// send imeiNumber
				socket.SendExact(Common
						.intToByteArray(CommonEnums.ConnectType.Login.ordinal()));
				byte[] buffer = imeiNumber.getBytes();
				int len = buffer.length;
				socket.SendExact(Common.intToByteArray(len));
				socket.SendExact(buffer);
				// send phoneNumber
				buffer = phoneNumber.getBytes();
				len = buffer.length;
				socket.SendExact(Common.intToByteArray(len));
				socket.SendExact(buffer);

				// read result from server
				buffer = new byte[4];
				socket.ReadExact(buffer);
				Message message = handler.obtainMessage(
						Constant.HANDLER_LOGIN_RESULT,
						Common.byteArrayToInt(buffer));
				handler.sendMessage(message);
			} else {				
				Message message = handler.obtainMessage(
						Constant.HANDLER_LOGIN_RESULT,
						CommonEnums.RetCode.SystemError.ordinal());
				handler.sendMessage(message);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			Message message = handler.obtainMessage(
					Constant.HANDLER_LOGIN_RESULT,
					CommonEnums.RetCode.SystemError.ordinal());
			handler.sendMessage(message);
			e.printStackTrace();
		}

	}

}
